<template>
  <div class="flyweight-demo">
    <h1>享元模式示例 - 图书管理系统</h1>
    
    <div class="controls">
      <button @click="addBooks">添加图书</button>
      <button @click="clearBooks">清除图书</button>
      <div class="stats">
        当前享元对象数量: {{ flyweightCount }}
        当前图书实例数量: {{ books.length }}
      </div>
    </div>

    <div class="books-container">
      <div v-for="(book, index) in books" :key="index" class="book-card">
        <pre>{{ book.display() }}</pre>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { BookFlyweightFactory, BookFlyweight, type BookExtrinsicState } from '../patterns/Flyweight';

const factory = BookFlyweightFactory.getInstance();
const books = ref<BookFlyweight[]>([]);
const flyweightCount = ref(0);

const addBooks = () => {
  // 添加10本图书
  for (let i = 0; i < 10; i++) {
    const isbn = `ISBN-${Math.floor(Math.random() * 1000)}`;
    const intrinsicState = factory.getFlyweight(isbn);
    
    const extrinsicState: BookExtrinsicState = {
      location: `Shelf ${Math.floor(Math.random() * 10)}`,
      borrower: `User ${Math.floor(Math.random() * 100)}`,
      dueDate: new Date(Date.now() + Math.random() * 30 * 24 * 60 * 60 * 1000).toLocaleDateString()
    };

    books.value.push(new BookFlyweight(intrinsicState, extrinsicState));
  }
  flyweightCount.value = factory.getFlyweightCount();
};

const clearBooks = () => {
  books.value = [];
};

onMounted(() => {
  flyweightCount.value = factory.getFlyweightCount();
});
</script>

<style scoped>
.flyweight-demo {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.controls {
  margin: 20px 0;
  display: flex;
  gap: 10px;
  align-items: center;
}

.stats {
  margin-left: 20px;
  padding: 10px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.books-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.book-card {
  padding: 15px;
  border: 1px solid #ddd;
  border-radius: 8px;
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

button {
  padding: 8px 16px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

button:hover {
  background-color: #45a049;
}

pre {
  white-space: pre-wrap;
  font-family: monospace;
  margin: 0;
}
</style> 